package com.weiaibenpao.demo.chislim.sport;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocationClient;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.jaeger.library.StatusBarUtil;
import com.weiaibenpao.demo.chislim.Interface.OnSportRecordListener;
import com.weiaibenpao.demo.chislim.R;
import com.weiaibenpao.demo.chislim.RunningDataView;
import com.weiaibenpao.demo.chislim.RunningPreferences;
import com.weiaibenpao.demo.chislim.RunningService;
import com.weiaibenpao.demo.chislim.RunningUtils;
import com.weiaibenpao.demo.chislim.bean.AddSportsBean;
import com.weiaibenpao.demo.chislim.bean.UserBean;
import com.weiaibenpao.demo.chislim.ui.BaseRunningActivity;
import com.weiaibenpao.demo.chislim.ui.MusicTypeActivity;
import com.weiaibenpao.demo.chislim.ui.SportHomeRemberActivity;
import com.weiaibenpao.demo.chislim.util.ACache;
import com.weiaibenpao.demo.chislim.util.GetIntentData;
import com.weiaibenpao.demo.chislim.util.SlideUnlockView;
import com.weiaibenpao.demo.chislim.util.SpeechUtil;
import com.weiaibenpao.demo.chislim.util.Utils;
import com.weiaibenpao.demo.chislim.util.VoicePlayerUtil;

import java.text.DecimalFormat;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.weiaibenpao.demo.chislim.RunningService.KM_PACE;

public class FavouriteMapOutHomeActivity extends BaseRunningActivity implements LocationSource, RunningService.OnDataUpdatedListener {

    private static final int LOCATION_TIME_INTERVAL = 4000;

    @BindView(R.id.iv_back)
    ImageView iv_back;
    @BindView(R.id.titleTv)
    TextView titleTv;
    @BindView(R.id.mapView)
    MapView mapView;

    @BindView(R.id.showView)
    LinearLayout showView;
    @BindView(R.id.start)
    ImageView start;
    @BindView(R.id.lock)
    ImageView lock;
    @BindView(R.id.stop)
    TextView stop;

    @BindView(R.id.countdown_view)
    TextView countdownView;
    @BindView(R.id.running_data_view)
    RunningDataView runningDataView;

    @BindView(R.id.dis)
    TextView dis;
    @BindView(R.id.sportTime)
    TextView sportTime;
    @BindView(R.id.tv_steps)
    TextView tv_steps;
    @BindView(R.id.mySpeed)
    TextView mySpeed;
    @BindView(R.id.myCalories)
    TextView myCalories;
    @BindView(R.id.switch_layout)
    LinearLayout switchLayout;

    private ACache mCache;   //保存零食数据

    private AMap aMap;
    private AMapLocationClient locationClient = null;

    private boolean mIsStart = false;

    private RunningService mService;  //服务对象

    Context context;

    /**
     * 0 服务启动
     * 1 正常运动
     * 2 暂停
     * 3 继续
     * 4 停止
     */
    private int state;

    ArrayList<PolylineOptions> latLongList;
    Intent myIntent;
    double disPlan;// 计划跑步距离

    String disData = "0";                //当前运动距离
    String cor = "0";                    //卡路里
    String sporttime = "0";             //时间
    String step = "0";

    Intent intentServices;    //启动

    WindowManager wm;
    int widthScreen;
    int heightScreen;
    boolean screenFlag = false;

    int i = 0;

    double cenLat = 39.90866;      //当前地图中心点
    double cenLong = 116.397486;
    float zoom = 15;             //缩放比例

    String imageUrl;
    String imageUrlline;

    private VoicePlayerUtil voicePlayerUtil;
    private SharedPreferences mSharedPreferences;
    DecimalFormat decimalFormat;

    private ImageView imageView; //坐标点的小人标记

    LatLng latLng1;   //起点
    LatLng latLng2;   //终点

    int disTab;
    private ArrayList<LatLng> mTable = new ArrayList<>();
    boolean flags = true;

    GetIntentData getIntentData;

    /**
     * 绘制跑步轨迹
     */
    ArrayList<LatLng> arrayListSports = new ArrayList<>();

    private boolean isFirstRun = true;

    StringBuilder locusphoto = new StringBuilder("");             //轨迹
    StringBuilder frequencyphoto = new StringBuilder("");        //步频图
    StringBuilder stridephoto = new StringBuilder("");           //步幅图
    StringBuilder runspace = new StringBuilder("");              //配速列表
    StringBuilder heightphoto = new StringBuilder("");           //海拔图

    String heighData = "0";
    String runsData = "0";
    String strideData = "0";
    String frequencyData = "0";
    String kmNum = "0";
    String sport_time = "0";
    String km_pace;

    private ProgressDialog mProgressDialog;
    SlideUnlockView slideUnlockView;   //滑动解锁按钮


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_running);
        StatusBarUtil.setColor(this, getResources().getColor(R.color.ku_bg), 0);
        ButterKnife.bind(this);

//        voicePlayerUtil = new VoicePlayerUtil(this);
        context = getApplicationContext();
        mCache = ACache.get(context);
        mCache.put("state", "0");
        getIntentData = new GetIntentData();

        latLongList = FavouritePicActivity.latLongList;

        mapView.onCreate(savedInstanceState);                         // 此方法必须重写
        initMap();
        huizhi();
        getState();

        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setCancelable(false);
        mProgressDialog.setMessage("上传中...");

        titleTv.setText("户外跑");

        myIntent = getIntent();
        disPlan = myIntent.getDoubleExtra("dis", 1000);
        cenLat = myIntent.getDoubleExtra("cenLat", 39.90866);     //获取地图中心点
        cenLong = myIntent.getDoubleExtra("cenLong", 116.397486);   //获取地图中心点
        zoom = myIntent.getFloatExtra("zoom", 15);
        setIntro(cenLat, cenLong, zoom);                        //设置地图中心点

        latLng1 = new LatLng(0, 0);
        latLng2 = new LatLng(0, 0);


        decimalFormat = new DecimalFormat("0.00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
        //判断是否跑步还在继续
       /* int state = RunningPreferences.getInstance().getRunningState();
        if (state == RunningService.RUNNING) {
            lock.setVisibility(View.VISIBLE);
            stop.setVisibility(View.VISIBLE);
            start.setImageResource(R.drawable.ic_finish);
            //还在跑步
            restoreDataDisplay();//由于服务端的回调有过滤，例如如果精度不满足，就不回调，所以这里进行一次手动恢复现场
        } else if (state == RunningService.PAUSE) {
            lock.setVisibility(View.VISIBLE);
            stop.setVisibility(View.VISIBLE);
            start.setImageResource(R.drawable.ic_finish);
            restoreDataDisplay();//从暂停状态恢复，需要在前端手动恢复一下显示，因为此时服务也是Pause状态，不会回调更新数据
        }*/

        initAction();

        getTotalNum();
        setMarkerRun();
        initStartSportMark();
        initView();
    }

    public void initView() {
        ///锁屏
        slideUnlockView = (SlideUnlockView) findViewById(R.id.slideUnlockView);
        slideUnlockView.setOnUnLockListener(new SlideUnlockView.OnUnLockListener() {
            @Override
            public void setUnLocked(boolean lock) {
                // 如果是true，证明解锁
                if (lock) {

                    // 重置一下滑动解锁的控件
                    slideUnlockView.reset();
                    // 让滑动解锁控件消失
                    slideUnlockView.setVisibility(View.GONE);
                    switchLayout.setVisibility(View.VISIBLE);
                }
            }
        });
    }


    private void restoreDataDisplay() {
        dis.setText(String.valueOf(RunningPreferences.getInstance().getRunningDistance()));
        // sportTime.setText(getHmsTime((int) (RunningPreferences.getInstance().getRunningTime() / 1000)));
        //tv_steps.setText(String.valueOf(RunningPreferences.getInstance().));
        mySpeed.setText(String.valueOf(RunningPreferences.getInstance().getRunningPace()));
        //  myCalories.setText(String.valueOf(RunningPreferences.getInstance().getRunningPace()));
    }


    public void initMap() {
        aMap = mapView.getMap();

        aMap.setTrafficEnabled(true);// 显示实时交通状况
        //地图模式可选类型：MAP_TYPE_NORMAL,MAP_TYPE_SATELLITE,MAP_TYPE_NIGHT
        aMap.setMapType(AMap.MAP_TYPE_NORMAL);// 卫星地图模式

        wm = this.getWindowManager();

        widthScreen = wm.getDefaultDisplay().getWidth();
        heightScreen = wm.getDefaultDisplay().getHeight();


    }

    @OnClick({R.id.iv_back, R.id.stop, R.id.start, R.id.lock,R.id.music_tv})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.music_tv:
                Intent intent = new Intent(this , MusicTypeActivity.class);
                startActivity(intent);
                break;
            case R.id.iv_back:
                finish();
                break;
            case R.id.lock:
                Log.i("事件", "锁屏");
                slideUnlockView.setVisibility(View.VISIBLE);
                switchLayout.setVisibility(View.GONE);
                break;
            case R.id.stop:
                if (mService != null) {
                    if (mService.getRunningState() == RunningService.RUNNING) {
                        stop.setText("继续");
//                        voicePlayerUtil.startVoice("跑步暂停");
                        SpeechUtil.getInstance().speak("暂停跑步");
                        mService.setState(RunningService.PAUSE);
                    } else if (mService.getRunningState() == RunningService.PAUSE) {
                        if(goEnableGPS()) return;
                        stop.setText("暂停");
//                        voicePlayerUtil.startVoice("跑步继续");
                        SpeechUtil.getInstance().speak("继续跑步");
                        mService.setState(RunningService.RUNNING);
                    }
                }
                break;
            case R.id.start:             //倒计时后  开始 暂停 的按钮
                Log.i("事件", " 开始 暂停");
                //考虑服务一直在，但是界面销毁然后重新进入时候的UI
                if (mService != null) {
                    if (mService.hasOngoingRunning()) {

//                        if (cor == "" || cor == null) {
//                            cor = "0";
//                        }
                        if(TextUtils.isEmpty(cor)) cor ="0";
                        if (heightphoto.length() > 0) {
                            heightphoto = heightphoto.deleteCharAt(heightphoto.length() - 1);
                        }
                        if (frequencyphoto.length() > 0) {
                            frequencyphoto = frequencyphoto.deleteCharAt(frequencyphoto.length() - 1);
                        }
                        if (stridephoto.length() > 0) {
                            stridephoto = stridephoto.deleteCharAt(stridephoto.length() - 1);
                        }
                        if (runspace.length() > 0) {
                            runspace = runspace.deleteCharAt(runspace.length() - 1);
                        }
                        if (locusphoto.length() > 0) {
                            locusphoto = locusphoto.deleteCharAt(locusphoto.length() - 1);
                            Log.i("经纬度", locusphoto.toString());
                        }
                        //结束弹框
                        if (Float.parseFloat(disData) * 1000 > THRESHOLD_DISTANCE) {
                            showUploadDialog();
                        } else {
                            showNotUploadDialog();
                        }
                    } else {
                        if(goEnableGPS()) return;
                        if (isFirstRun) {
                            isFirstRun = false;
                            startCountdown();   //倒计时
                        }
                    }
                }
                break;
        }
    }

    @Override
    public void onGPSStateChanged(boolean isEnabled) {
        super.onGPSStateChanged(isEnabled);
        if(isEnabled){
//            if(mService!=null && mService.getRunningState() == RunningService.PAUSE ) onClick(tvStop);
        } else {
            if(mService!=null && mService.getRunningState() == RunningService.RUNNING ) onClick(stop);
        }
    }

    public void initAction() {
        getIntentData.setOnSportRecordListener(new OnSportRecordListener() {
            @Override
            public void onUploadSuccess(Object object) {
                AddSportsBean.DataBean dataBean = (AddSportsBean.DataBean) object;
                SportRecordShareActivity.openActivity(FavouriteMapOutHomeActivity.this, dataBean.getUrl(),disData);
                if (mProgressDialog != null) mProgressDialog.dismiss();
                doFinish();
            }

            @Override
            public void onUploadFailed(String str) {
                Toast.makeText(FavouriteMapOutHomeActivity.this,str,Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void startCountdown() {
        countdownView.setVisibility(View.VISIBLE);
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 3; i >= -1; i--) {
                    try {
                        final int index = i;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (index > 0) {
//                                    voicePlayerUtil.startVoice(String.valueOf(index));
                                    SpeechUtil.getInstance().speak(String.valueOf(index));
                                    countdownView.setText(String.valueOf(index));
                                } else if (index == 0) {
//                                    voicePlayerUtil.startVoice("跑步开始");
                                    SpeechUtil.getInstance().speak("跑步开始");
                                    countdownView.setText("Go!");
                                } else {
                                    countdownView.setVisibility(View.GONE);
                                    mService.setState(RunningService.RUNNING);
                                    lock.setVisibility(View.VISIBLE);
                                    stop.setVisibility(View.VISIBLE);
                                    start.setImageResource(R.drawable.ic_finish);
                                }
                            }
                        });
                        Thread.sleep(1000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    /**
     * 绘制预设轨迹
     */
    PolylineOptions polylineOptionsY;
    public void huizhi() {
        for (int i = 0; i < latLongList.size(); i++) {
            polylineOptionsY = latLongList.get(i);

            polylineOptionsY.visible(true).width(15).zIndex(200);
            polylineOptionsY.color(Color.argb(255, 24, 159, 246));
            //加入对应的颜色,使用colorValues 即表示使用多颜色，使用color表示使用单色线
            //polylineOptions.colorValues(WalkUtil.getColorList(latLongList.size() / 144 + 1, this));
            //加上这个属性，表示使用渐变线
            polylineOptionsY.useGradient(true);
            aMap.addPolyline(polylineOptionsY);
        }
    }

    /**
     * 总点数
     *
     * @return
     */
    int numTotal = 0;
    ArrayList arrayListNum;

    private int getTotalNum() {
        arrayListNum = new ArrayList();
        for (int i = 0; i < latLongList.size(); i++) {

            arrayListNum.add(latLongList.get(i).getPoints().size());
            numTotal += latLongList.get(i).getPoints().size();

            for (int j = 0; j < latLongList.get(i).getPoints().size(); j++) {
                if (j == 0 && i == 0) {
                    latLng1 = latLongList.get(i).getPoints().get(0);
                }
                locusphoto = locusphoto.append(latLongList.get(i).getPoints().get(j).longitude + "," + latLongList.get(i).getPoints().get(j).latitude + ":");   //轨迹
            }

            if (locusphoto.length() > 0) {
                locusphoto = locusphoto.deleteCharAt(locusphoto.length() - 1);
                locusphoto.append(";");
            }
        }
            return numTotal;
    }


    int n = 0;

    private void getNowNum(int dis, double disPlan) {

        if (dis >= disPlan) {
            n = numTotal;
        } else {
            n = (int) (((float) dis / disPlan) * numTotal);
            huizhiSports(n);
        }
        Log.i("点数", "----------当前点数： " + n + "----------总点数： " + numTotal);

    }

    //当前连线的点数
    int p = 0;
    int k = 0;
    /**
     * @param num  每次画点的数
     */
    PolylineOptions polylineOptions;
    LatLng latLngRun;
    Polyline polyline;

    public void huizhiSports(int n) {
        if(polylineOptions != null){
            polylineOptions = null;
        }

        if (n >= numTotal) {
            n = numTotal;
        }

        for(int i = 0; i < latLongList.size(); i++){
            if(n > (int) arrayListNum.get(i)){
                p = (int) arrayListNum.get(i);
                n = n - p;
            }else{
                /*k = i-1;
                if(i == 0){
                    k = i;
                }*/

                break;
            }
        }

        for (int i = k; i < latLongList.size(); i++) {
         //   n = k;
            polylineOptions = new PolylineOptions();
            polylineOptions.visible(true).width(15).zIndex(200);
            polylineOptions.color(Color.argb(255, 204, 53, 143));
            if (n > (int) arrayListNum.get(i)) {
                p = (int) arrayListNum.get(i);
                n = n - p;
         //       k = n;
                for (int j = 0; j < p; j++) {
                    polylineOptions.add(latLongList.get(i).getPoints().get(j));
                    latLngRun = latLongList.get(i).getPoints().get(j);
                }
                locationImg(latLngRun);
                getSpeed();

                if (polyline != null) {
                    //polyline.remove();

                    polyline = null;
                }

                polyline = aMap.addPolyline(polylineOptions);
            } else {
                for (int j = 0; j < n; j++) {
                    polylineOptions.add(latLongList.get(i).getPoints().get(j));
                    latLngRun = latLongList.get(i).getPoints().get(j);
                }
                locationImg(latLngRun);
                getSpeed();

                if (polyline != null) {
                    //polyline.remove();
                    polyline = null;
                }
                k = i;
                polyline = aMap.addPolyline(polylineOptions);
                break;
            }
        }
    }

    /**
     * 当前位置标记
     */

    public void locationImg(LatLng latLng) {
        if (marker != null) {
            marker.remove();
            marker = null;
        }
        markerRun.position(latLng);
        marker = aMap.addMarker(markerRun);
    }

    //设置帧动画
    ArrayList iconList;
    MarkerOptions markerRun = new MarkerOptions();
    Marker marker;

    public void setMarkerRun() {
        iconList = new ArrayList();
        iconList.add(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                .decodeResource(getResources(), R.drawable.run_1)));
        iconList.add(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                .decodeResource(getResources(), R.drawable.run_2)));
        iconList.add(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                .decodeResource(getResources(), R.drawable.run_3)));
        iconList.add(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                .decodeResource(getResources(), R.drawable.run_4)));
        iconList.add(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                .decodeResource(getResources(), R.drawable.run_5)));
        iconList.add(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                .decodeResource(getResources(), R.drawable.run_6)));
        iconList.add(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                .decodeResource(getResources(), R.drawable.run_7)));
        iconList.add(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                .decodeResource(getResources(), R.drawable.run_8)));

        markerRun.draggable(false);   //设置Marker可拖动
        markerRun.icons(iconList);
        markerRun.period(5);        //值越小刷新的越快
        // 将Marker设置为贴地显示，可以双指下拉地图查看效果
        markerRun.setFlat(true);//设置marker平贴地图效果
    }

    public void getSpeed() {
        //经纬度拼接

        frequencyphoto.append(sport_time).append(":").append(frequencyData).append(",");
        stridephoto.append(sport_time).append(":").append(strideData).append(",");
        heightphoto.append(sport_time).append(":").append(heighData).append(",");

        Log.i("上传的数据:", "坐标：" + locusphoto.toString() + "  步频：" + frequencyphoto + " 步幅 ：" + stridephoto + "   配速：" + runspace + "  海拔：" + heightphoto);
    }

    //22'10''    转换为   秒
    public String changeTime(String runsData) {
        String array[] = runsData.split("'");
        int min = strSpit(array[0]);
        int second = strSpit(array[1]);
        return "" + (min * 60 + second);
    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        //mLocationLinstener = onLocationChangedListener;
    }

    @Override
    public void deactivate() {
        // mLocationLinstener = null;
    }

    public void getState() {
        Log.i("跑步", state + "-------------------------------------");
        if (state == 1 || state == 3) {                   //运动
            showView.setVisibility(View.VISIBLE);

            start.setImageResource(R.mipmap.stop);
        } else if (state == 2) {
            showView.setVisibility(View.VISIBLE);

            start.setImageResource(R.mipmap.sportcontinue);
        }
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onStart() {
        super.onStart();
        intentServices = new Intent(FavouriteMapOutHomeActivity.this, RunningService.class);
        intentServices.putExtra(RunningService.RUNNING_ACTIVITY, getClass().getCanonicalName());
        intentServices.putExtra(RunningService.NEED_EXTRA_DATA, true);
        startService(intentServices);

        bindService(intentServices, connection, Context.BIND_AUTO_CREATE);
    }

    /**
     * 获取服务对象
     */
    public ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            RunningService.LocalBinder binder = (RunningService.LocalBinder) service;
            mService = binder.getService();

            mService.registerOnDataUpdatedListener(FavouriteMapOutHomeActivity.this);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mService.onDestroy();
        }
    };

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
        deactivate();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        if (null != locationClient) {
            locationClient.onDestroy();
        }
        unbindService(connection);
        if (mService != null) mService.unRegisterOnDataUpdatedListener();

        // unregisterReceiver(receiver);
        //receiver = null;
    }

    //ArrayList<LatLng> latLngList = new ArrayList();

    @Override
    public void onDataUpdated(Bundle data) {
        //    Log.i("坐标","这里更新界面");
        runningDataView.setView(data);

        mTable = data.getParcelableArrayList("mTable");                            //整公里坐标点
        cor = data.getString(RunningService.CALORIE);                                    //卡路里
        sporttime = data.getString("sporttime");                                    //时间
        step = data.getString(RunningService.STEP);                                  //步数
        flags = data.getBoolean("flags", true);                                    //判断是否为GPS  true代表为Gps
        state = data.getInt("state", 0);
        km_pace = data.getString(KM_PACE);                                       //整公里配速

        getState();

        heighData = data.getString(RunningService.ALTITUDE);                    //海拔
        runsData = data.getString(RunningService.PACE);                         //配速
        strideData = data.getString(RunningService.STRIDE);                     //步幅
        frequencyData = data.getString(RunningService.FREQUENCY);              //步频
        Log.i("上传的数据", "海拔：" + heighData + "---- 配速" + runsData + "----- 步幅：" + strideData + "-----步频：" + frequencyData);
        disData = decimalFormat.format(data.getFloat(RunningService.DISTANCE) / 1000);

        if (!TextUtils.isEmpty(data.getString(RunningService.KM_VALUE))) {
            runspace.append(kmNum).append(":").append(km_pace).append(":").append(sport_time).append(",");
        }

        dis.setText(disData);

        tv_steps.setText(step);
        mySpeed.setText(runsData);

        myCalories.setText(cor + "");

        if (disTab != (int) (Float.parseFloat(disData) * 1000)) {

            //todo 这里更新界面
            getNowNum((int) (Float.parseFloat(disData) * 1000), disPlan);

            disTab = (int) (Float.parseFloat(disData) * 1000);
        }
        setIntro(cenLat, cenLong, zoom);
    }

    @Override
    public void onRunningTime(final int runningTime) {
        sporttime = RunningUtils.getHmsTime(runningTime);

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                sportTime.setText(sporttime);
                sport_time = String.valueOf(runningTime);
            }
        });
    }

    public void goIntent() {
        Intent intent = new Intent(context, SportHomeRemberActivity.class);

        intent.putExtra("sportDis", Integer.parseInt(disData));
        intent.putExtra("sportTime", sporttime);
        //intent.putExtra("sportCor", Integer.parseInt(cor));
        intent.putExtra("sportCor", 15);
        intent.putExtra("imageUrl", imageUrl);
        intent.putExtra("imageUrlline", imageUrlline);

        startActivity(intent);

        mIsStart = false;
        // mService.setNum(4);
        unbindService(connection);                         //解除绑定服务
        mService.stopService(intentServices);         //关闭启动式服务
        mService.stopSelf();
        finish();
    }


    /**
     * 切换地图显示中心点
     */
    public void setIntro(double latNow, double longNow, float n) {
        LatLng marker1 = new LatLng(latNow, longNow);
        //设置中心点和缩放比例
        aMap.moveCamera(CameraUpdateFactory.changeLatLng(marker1));
        aMap.moveCamera(CameraUpdateFactory.zoomTo(n));
    }

    /**
     * 绘制起点和终点
     * int startX;    //起点
     * int startY;
     * int stopX;    //终点
     * int stopY;
     */
    public void initStartSportMark() {

        MarkerOptions markerOption = new MarkerOptions();
        markerOption.position(latLng1);
        markerOption.draggable(false);   //设置Marker可拖动
        markerOption.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                .decodeResource(getResources(), R.drawable.staring_point)));
        // 将Marker设置为贴地显示，可以双指下拉地图查看效果
        markerOption.setFlat(true);//设置marker平贴地图效果
        aMap.addMarker(markerOption);

        markerOption.position(latLng2);
        markerOption.draggable(false);   //设置Marker可拖动
        markerOption.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                .decodeResource(getResources(), R.drawable.end_point)));
        // 将Marker设置为贴地显示，可以双指下拉地图查看效果
        markerOption.setFlat(true);//设置marker平贴地图效果
        aMap.addMarker(markerOption);
    }

    //将字符串时间格式转化为int
    public int returnTime(String time) {
        String[] array = time.split(":");
        int hour = strSpit(array[0]);
        int min = strSpit(array[1]);
        int second = strSpit(array[2]);

        return 3600 * hour + min * 60 + second;
    }

    public int strSpit(String time) {
        if (time.charAt(0) == '0') {
            return Integer.parseInt(String.valueOf(time.charAt(1)));
        } else {
            return Integer.parseInt(time);
        }
    }

    /**
     * 重写onKeyDown方法
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            Log.e("onKeyDown", "------------------------------->");

            if (mService != null && mService.hasOngoingRunning()) {
                showDialog();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 这是兼容的 AlertDialog
     */
    private void showDialog() {
      /*
          这里使用了 android.support.v7.app.AlertDialog.Builder
          可以直接在头部写 import android.support.v7.app.AlertDialog
          那么下面就可以写成 AlertDialog.Builder
      */
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("跑步提示");
        builder.setMessage("跑步还在进行中，请结束后退出？");
        builder.setNegativeButton("结束", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

                if (Float.parseFloat(disData) * 1000 > THRESHOLD_DISTANCE) {
                    showUploadDialog();
                } else {
                    showNotUploadDialog();
                }

//                voicePlayerUtil.startVoice("跑步结束");
                SpeechUtil.getInstance().speak("跑步结束");

                mIsStart = false;
                mService.setState(RunningService.FINISH);
                //  goToRecord();   //跳转到记录界面
                stopService(intentServices);
            }
        });
        builder.setPositiveButton("继续", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });
        builder.show();
    }

    private static final int THRESHOLD_DISTANCE = 100;//单位“千米”

    private void showUploadDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("跑步提示");
        builder.setMessage("是否保存并上传数据？");
        builder.setNegativeButton("放弃", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                doFinish();
            }
        });
        builder.setPositiveButton("保存", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                uploadRunningData();
            }
        });
        builder.setCancelable(false);
        // AlertDialog dialog = builder.create();
        builder.show();
        // dialog.getButton(dialog.BUTTON_POSITIVE).setTextColor(Color.parseColor("#189ff6"));
        // dialog.getButton(dialog.BUTTON_NEGATIVE).setTextColor(Color.parseColor("#666666"));
    }

    private void showNotUploadDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("跑步提示");
        builder.setMessage("本次跑步距离太短，无法保存，确定放弃？");
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //do nothing
            }
        });
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                doFinish();
            }
        });
        builder.setCancelable(false);
        //AlertDialog dialog = builder.create();
        builder.show();
        // dialog.getButton(dialog.BUTTON_POSITIVE).setTextColor(Color.parseColor("#189ff6"));
        // dialog.getButton(dialog.BUTTON_NEGATIVE).setTextColor(Color.parseColor("#666666"));
    }

    private void doFinish() {
        if (mService != null) mService.setState(RunningService.FINISH);
//        goToRecord();
        finish();
    }

    private void uploadRunningData() {
        if (isDestroyed()) {
            return;
        }
        if (!Utils.isNetWorkConnected()) {
            Toast.makeText(this, "亲，网络连了么？", Toast.LENGTH_SHORT).show();
            return;
        }

        if (mProgressDialog != null) mProgressDialog.show();

        getIntentData.uploadRunningData(UserBean.getUserBean().userId, 5,
                "", "", "", cor, "", "", "", disData, "", "", returnTime(sporttime), step, String.valueOf(disPlan),
                heightphoto.toString(),
                frequencyphoto.toString(),
                stridephoto.toString(),
                runspace.toString(),
                locusphoto.toString(), String.valueOf(numTotal));
    }
}
